package com.ych.util.logUtil;

import com.alibaba.fastjson.JSON;
import com.ych.beans.Log;
import com.ych.beans.Message;
import com.ych.beans.UserManager;
import com.ych.controller.OrgaController;
import com.ych.controller.RoleController;
import com.ych.controller.UserController;
import com.ych.dao.LogDao;
import com.ych.util.SessionNameEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.EventListener;
import java.util.EventObject;

/**
 * 此切面用于向数据库中写入操作记录，配合@AddLog使用
 */
@Component
@Aspect
public class LogAspect implements EventListener {
    @Autowired
    LogDao dao;
    @Autowired
    StringRedisTemplate temp;

    @Pointcut("@annotation(com.ych.util.logUtil.AddLog)")
    public void addLog(){}

    @AfterReturning(value = "addLog()",returning = "result")
    public void afterReturn(JoinPoint joinPoint,Message result) throws Throwable{
        //创建一个日志对象并将操作时间设置为当前时间
        Log log = new Log();
        log.setOperTime(new Date(System.currentTimeMillis()));

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        try {
            //获取登录缓存
            String sessionId = attributes.getSessionId();
            String userJSONString = (String) temp.opsForHash().get(SessionNameEnum.LOGIN.getName(), sessionId);
            UserManager user = JSON.parseObject(userJSONString,UserManager.class);
            log.setUsername(user.getUsername());

            //获取目标类判定操作对象
            String className = joinPoint.getTarget().getClass().getName();

            HttpServletRequest request = attributes.getRequest();
            String method = request.getMethod();

            String operName = "";
            if (method.startsWith("POST")){
                log.setOperType("add");
                operName += "添加";
            }else if (method.startsWith("GET")){
                log.setOperType("select");
                operName += "选择";
            }else if (method.startsWith("DELETE")){
                log.setOperType("delete");
                operName += "删除";
            }else if (method.startsWith("PUT")){
                log.setOperType("update");
                operName += "修改";
            }

            if (className.endsWith("OrgaController")){
                log.setModuleName("orga");
                operName += "组织";
            }else if (className.endsWith("RoleController")){
                log.setModuleName("role");
                operName += "角色";
            }else if (className.endsWith("UserController")){
                log.setModuleName("user");
                operName += "用户";
            }else if (className.endsWith("PermController")){
                log.setModuleName("perm");
                operName += "角色权限";
            }
            log.setOperContent(operName);
            log.setResult(result.isSuccess());
            dao.add(log);
        }catch (NullPointerException e){
            //考虑到测试需要，在无登录信息时认定为测试操作，正式项目需要删除
            System.out.println("当前无用户登录，测试操作");
        }
    }
}
